<script>
import ButtonList from '@/components/ButtonList'
import WrapTable from '@/components/WrapTable'
// import ButtonList from "@/components/ButtonList";
// import TableButtonList from "@/components/TableButtonList";
import addtable from '@/mixins/addtable'
import AjaxStore from '@/utils/store/proxyAjax'
import DialogForm from '@/components/DialogForm'
import RolePersonFenpei from './rolePersonFenpei/index.vue'
import RoleAuthorize from './roleAuthorize/roleAuthorize.vue'
import DataGroupConfig from './dataGroupConfig/dataGroupConfig.vue'
import { mapGetters } from 'vuex'
import store from './store.js'
import request from '@/utils/request'

export default {
  name: 'role-manage',
  mixins: [addtable, store],
  // mixins: [addtable, store, commonBreadCrumb, emitter],
  components: {
    RolePersonFenpei,
    RoleAuthorize,
    DataGroupConfig,
    WrapTable
    // ButtonList,
    // TableButtonList
  },
  computed: {
    ...mapGetters(['projectId', 'projectName', 'systemType']),
    roleAuthorizeUrl() {
      // if(!this.projectName){
      //   return '/v1/sys/role/grantFunction'
      // }else{
      //   return '/v1/sys/role/grantProjectFunction'
      // }
      return '/v1/sys/role/grantProjectFunction'
    },
    dialogConfigTitle() {
      return `${this.projectName}-数据组配置`
    },
    wrapTableOptWidth() {
      return this.projectId ? '180' : '150'
    }
  },
  provide() {
    return {
      role: this
    }
  },
  data() {
    return {
      dialogType: '',
      dialogFenpeiTitle: '人员分配',
      dialogAuthorizeTitle: '角色授权',
      idKey: 'roleId',
      delIdKey: 'roleId',
      delListIdKey: 'roleIds',
      roleId: '',
      roleName: '',
      projectIdSe: '',
      containerData: '',
      showInputFlag: true,
      inputPlaceholder: '输入角色名称搜索',

      addUrl: '/v1/yq/sys/roleApi/insert',
      updateUrl: '/v1/yq/sys/roleApi/update',
      delUrl: '/v1/sys/role/delete',
      delListUrl: '/v1/sys/role/deleteList',
      fenpeiUrl: '/v1/sys/role/grantRoleToUsersV3',
      getFenpeiUserInfoUrl: '/v1/sys/role/findUsersById',
      getRoleAuthorizeInfoUrl: '/v1/sys/role/findAllFunNodeTree',
      getHavedDataGroupsUrl: '/v1/yq/sys/roleApi/getByRoleId',
      updateActDataUrl: '/v1/sys/role/updateActData',
      url: '/v1/sys/role/findById',
      store: new AjaxStore({
        url: '/v1/yq/sys/roleApi/getDataTables'
      }),
      columns: [
        {
          prop: 'roleCode',
          label: '角色编码',
          sortable: true,
          width: '200',
          'show-overflow-tooltip': true,
          'header-align': 'center'
        },
        {
          prop: 'roleName',
          label: '角色名称',
          sortable: true,
          width: '200',
          'header-align': 'center'
        },
        // { prop: "projectId", label: "归属站点Id", sortable: true, width: "200", 'header-align': 'center' },
        {
          prop: 'projectName',
          label: '归属站点',
          sortable: true,
          width: '200',
          'header-align': 'center'
        },
        {
          prop: 'dataStatus',
          label: '状态',
          sortable: true,
          width: '100',
          'header-align': 'center',
          formatter: (row, column, cellValue) => (cellValue ? '启用' : '停用')
        },
        {
          prop: 'grantUsers',
          label: '已分配人员',
          sortable: true,
          'min-width': '240',
          'header-align': 'center',
          'show-overflow-tooltip': true
        },
        {
          prop: 'remark',
          label: '角色描述',
          sortable: true,
          'min-width': '240',
          'header-align': 'center',
          'show-overflow-tooltip': true
        }
      ],
      searchFields: [],
      searchModel: {},
      searchBtnList: [],
      toolPanelBtnList: this.toolPanelBtns,
      tableRowBtnList: this.tableRowBtns,
      formPanel: {
        add: {
          model: {
            projectId: '',
            roleId: '',
            roleCode: '',
            roleName: '',
            dataStatus: 1,
            json: '',
            version: '',
            creator: '',
            createdTime: '',
            updator: '',
            updatedTime: '',
            remark: '',
            grantUsers: '',
            flag: 1
          },
          fields: [
            {
              label: '角色名称',
              prop: 'roleName',
              placeholder: '输入角色名称',
              anchor: 24
            },
            {
              label: '归属站点',
              prop: 'projectId',
              placeholder: '请选择归属站点',
              xType: 'SelectConfig',
              isLocal: false,
              relatedFields: ['firstCateId', 'secondCateId'],
              anchor: 8,
              getData: () => {
                return request({
                  url: '/v1/yq/project/getProjectTextId',
                  method: 'get'
                }).then(({ data }) => {
                  return data.map(item => {
                    return {
                      value: /^\d+$/.test(item.id)
                        ? parseInt(item.id)
                        : item.id + '',
                      label: item.text,
                      ...item
                    }
                  })
                })
              }
            },
            {
              label: '状态',
              prop: 'dataStatus',
              xType: 'switch',
              anchor: 24,
              'active-value': 1,
              'inactive-value': 0
            },
            {
              label: '描述',
              prop: 'remark',
              placeholder: '输入描述',
              anchor: 24,
              type: 'textarea',
              rows: 4
            }
          ],
          rules: {
            roleName: [
              { required: true, message: '请输入角色名称', trigger: 'blur' }
            ],
            dataStatus: [
              { required: true, message: '请输入角色名称', trigger: 'blur' }
            ],
            projectId: [
              { required: true, message: '请选择归属站点', trigger: 'blur' }
            ]
          },
          title: '新增角色',
          type: 'ADD',
          ref: 'addForm',
          submitBtnList: this.addBtns
        },
        edit: {
          model: {
            projectId: '',
            roleId: '',
            roleCode: '',
            roleName: '',
            dataStatus: 0,
            json: '',
            version: '',
            creator: '',
            createdTime: '',
            updator: '',
            updatedTime: '',
            remark: '',
            grantUsers: ''
          },
          fields: [
            {
              label: '角色编码',
              prop: 'roleCode',
              placeholder: '输入角色编码',
              anchor: 24,
              disabled: true
            },
            {
              label: '角色名称',
              prop: 'roleName',
              placeholder: '输入角色名称',
              anchor: 24
            },
            {
              label: '归属站点',
              prop: 'projectId',
              disabled: true,
              placeholder: '请选择归属站点',
              xType: 'SelectConfig',
              isLocal: false,
              relatedFields: ['firstCateId', 'secondCateId'],
              anchor: 8,
              getData: () => {
                return request({
                  url: '/v1/yq/project/getProjectTextId',
                  method: 'get'
                }).then(({ data }) => {
                  return data.map(item => {
                    return {
                      value: /^\d+$/.test(item.id)
                        ? parseInt(item.id)
                        : item.id + '',
                      label: item.text,
                      ...item
                    }
                  })
                })
              }
            },
            {
              label: '状态',
              prop: 'dataStatus',
              xType: 'switch',
              anchor: 24,
              'active-value': 1,
              'inactive-value': 0
            },
            {
              label: '描述',
              prop: 'remark',
              placeholder: '输入描述',
              type: 'textarea',
              rows: 4,
              anchor: 24
            }
          ],
          rules: {
            roleName: [
              { required: true, message: '请输入角色名称', trigger: 'blur' }
            ],
            dataStatus: [
              { required: true, message: '请输入状态', trigger: 'blur' }
            ],
            projectId: [
              { required: true, message: '请选择归属站点', trigger: 'blur' }
            ]
          },
          title: '编辑角色',
          type: 'EDIT',
          ref: 'editForm',
          submitBtnList: this.editBtns
        },
        look: {
          model: {
            projectId: '',
            roleId: '',
            roleCode: '',
            roleName: '',
            dataStatus: 0,
            json: '',
            version: '',
            creator: '',
            createdTime: '',
            updator: '',
            updatedTime: '',
            remark: '',
            grantUsers: '',
            flag: 1
          },
          fields: [
            {
              label: '角色编码',
              prop: 'roleCode',
              placeholder: '输入角色编码',
              anchor: 24,
              disabled: true
            },
            {
              label: '角色名称',
              prop: 'roleName',
              placeholder: '输入角色名称',
              anchor: 24,
              disabled: true
            },
            {
              label: '状态',
              prop: 'dataStatus',
              xType: 'SelectCode.ENABLED',
              placeholder: '选择角色状态',
              anchor: 24,
              disabled: true
            },
            {
              label: '描述',
              prop: 'remark',
              placeholder: '',
              anchor: 24,
              disabled: true
            }
          ],
          rules: {},
          title: '查看角色',
          type: 'LOOK',
          ref: 'lookForm',
          submitBtnList: this.lookBtns
        }
      }
    }
  },
  methods: {
    handleEditSubmit() {
      return this.$refs.editForm
        .validate()
        .then(() => {
          return this.update(
            Object.assign(this.formPanel.edit.model, { flag: 1 })
          )
        })
        .then(({ success, message }) => {
          this.$message({
            type: success ? 'success' : 'error',
            message: message
          })
          if (success) {
            this.$refs.table.load()
            this.dialogType = ''
          } else {
            throw new Error(message)
          }
        })
        .catch(err => {
          console.log(err)
          return Promise.reject(err)
        })
    },
    handleInputClick(ev, val) {
      const params = {}
      params.q_roleName = val
      this.store._searchParams = params
      this.$refs.table.load(1, this.store.limit)
    },
    handleAuthorize(model) {
      this.roleName = model.roleName
      this.roleId = model.roleId
      this.dialogType = 'AUTHORIZE'
      this.projectIdSe = model.projectId
      this.$nextTick(() => {
        this.$refs.RoleAuthorize.roleId = this.roleId
        this.$refs.RoleAuthorize.currentLabelValue = this.roleName
      })
    },
    handleAuthorizeSubmit() {
      const params = {}
      params.roleId = this.roleId
      params.funIds = this.$refs.RoleAuthorize.getHalfANdAllCheckedList()
        .map(item => {
          return item
        })
        .join(',')
      // 加载 loading
      const loading = this.$loading({
        fullscreen: true,
        text: '请求发送中，请稍候',
        customClass: 'roleAuthorLoading'
      })
      this.roleAuthorize(params)
        .then(({ success, message }) => {
          if (success) {
            this.$message({
              type: 'success',
              message: message
            })
            this.dialogType = ''
          } else {
            this.$message({
              type: 'error',
              message: message
            })
          }
        })
        .catch(error => {
          console.log(error)
        })
        .then(() => {
          // 以服务的方式调用的 Loading 需要异步关闭
          this.$nextTick(() => {
            loading.close()
          })
        })
    },
    handleAuthorizeCancel() {
      this.$refs.RoleAuthorize.$refs.tree.emptyChecked()
      this.dialogType = ''
    },
    handleFenpei(model) {
      this.roleName = model.roleName
      this.roleId = model.roleId
      this.projectIdSe = model.projectId
      this.dialogType = 'FENPEI'
    },
    handleFenpeiSubmit() {
      this.selectedList = this.$refs.RolePersonFenpei.handleReturnSelectedList()
      let params = {}
      params.roleId = this.roleId
      let arr = []
      this.selectedList.forEach(element => {
        arr.push({
          userId: element.userId,
          deptId: element.deptId
        })
      })
      params.userDepts = arr
      params = JSON.stringify(params)
      this.fenpei(params)
        .then(({ success, message }) => {
          if (success) {
            this.$refs.table.load(1)
            this.$message({
              type: 'success',
              message: message
            })
            this.dialogType = ''
          } else {
            this.$message({
              type: 'error',
              message: message
            })
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    handleFenpeiCancel() {
      this.$refs.RolePersonFenpei.handleEmptySelectedList()
      this.dialogType = ''
    },
    handleConfig(model) {
      this.roleId = model.roleId
      this.dialogType = 'CONFIG'
    },
    handleConfigSubmit() {
      const params = {}
      params.actDataids = this.$refs.DataGroupConfig.handleReturnSelectedList()
        .map(item => {
          return item.datagroupId
        })
        .join('#')
      params.roleId = this.roleId
      this.updateDataGroupConfig(params)
        .then(({ success, message }) => {
          if (success) {
            this.$message({
              type: 'success',
              message: '数据组分配成功！'
            })
            this.dialogType = ''
            this.$refs.table.load(1)
          } else {
            this.$message({
              type: 'error',
              message: '数据组分配失败！'
            })
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    handleConfigCancel() {
      this.$refs.DataGroupConfig.handleEmptySelectedList()
      this.dialogType = ''
    },
    // eslint-disable-next-line
    renderCustom(h) {
      return [
        <DialogForm
          visible={this.dialogType === 'FENPEI'}
          width='750px'
          title={this.dialogFenpeiTitle}
          on-close={this.handleFenpeiCancel}>
          <RolePersonFenpei
            roleId={this.roleId}
            roleName={this.roleName}
            projectId={this.projectIdSe}
            ref='RolePersonFenpei'></RolePersonFenpei>
          <c-form ref='form' slot='footer'>
            <c-form-item class='submit-btn'>
              <ButtonList
                operateBtnList={this.FenpeiBtns}
                props-model={this.searchModel}></ButtonList>
            </c-form-item>
          </c-form>
        </DialogForm>,
        <DialogForm
          class='role-authorize-dialog'
          visible={this.dialogType === 'AUTHORIZE'}
          width='660px'
          title={this.dialogAuthorizeTitle}
          on-close={this.handleAuthorizeCancel}>
          <RoleAuthorize
            ref='RoleAuthorize'
            projectId={this.projectIdSe}></RoleAuthorize>
          <c-form ref='form' slot='footer'>
            <c-form-item class='submit-btn'>
              <ButtonList
                operateBtnList={this.AuthorizeBtns}
                props-model={this.searchModel}></ButtonList>
            </c-form-item>
          </c-form>
        </DialogForm>,
        <DialogForm
          visible={this.dialogType === 'CONFIG'}
          width='750px'
          title={this.dialogConfigTitle}
          on-close={this.handleConfigCancel}>
          <DataGroupConfig ref='DataGroupConfig' />
          <c-form ref='form' slot='footer'>
            <c-form-item class='submit-btn'>
              <ButtonList
                operateBtnList={this.ConfigBtns}
                props-model={this.searchModel}
              />
            </c-form-item>
          </c-form>
        </DialogForm>
      ]
    },
    renderWrapTable(h) {
      return (
        <WrapTable
          ref='table'
          getData={this.getData}
          total={this.total}
          data={this.data}
          fields={this.columns}
          selectionCol={false}
          tooltip-effect='dark'
          border
          stripe
          default-sort={{ prop: 'funId', order: 'descending' }}
          on-selection-change={this.handleSelectionChange}
          on-row-dblclick={this.handleCurrentChange}>
          {this.searchBtnList && this.searchBtnList.length > 0 ? (
            <SearchForm
              items={this.searchFields}
              props-model={this.searchModel}
              slot='searchPanel'
              ref='searchForm'>
              <ButtonList
                operateBtnList={this.searchBtnList}
                props-model={this.searchModel}></ButtonList>
            </SearchForm>
          ) : (
            ''
          )}

          <c-row slot='toolPanel' class='toolPanel'>
            {this.toolPanelBtnList && this.toolPanelBtnList.length ? (
              <c-col
                span={this.btnListWidthPercent}
                offset={this.btnListWidthOffset}>
                <ButtonList operateBtnList={this.toolPanelBtnList}></ButtonList>
              </c-col>
            ) : (
              ''
            )}
            <c-col
              span={this.searchInputWidthPercent}
              offset={this.searchInputWidthOffset}>
              {this.showInputFlag ? (
                <c-input
                  class='search-input'
                  placeholder={this.inputPlaceholder}
                  size='small'
                  on-input={event => {
                    this.searchInput = event
                  }}
                  nativeOnKeydown={ev => {
                    ev.keyCode === 13
                      ? this.handleInputClick(ev, this.searchInput)
                      : null
                  }}>
                  <i
                    slot='suffix'
                    class='el-input__icon el-icon-search'
                    on-click={ev =>
                      this.handleInputClick(ev, this.searchInput)
                    }></i>
                </c-input>
              ) : (
                ''
              )}
            </c-col>
          </c-row>

          <c-table-column
            label='操作'
            align='center'
            slot='toolbar'
            fixed='right'
            width={this.wrapTableOptWidth}
            {...{
              scopedSlots: {
                default: scope => {
                  return (
                    <TableButtonList
                      operateBtnList={
                        scope.row.roleId === 1
                          ? this.tableRowBtnsWithoutEditAndDel
                          : this.tableRowBtns2
                      }
                      props-model={scope.row}></TableButtonList>
                  )
                }
              }
            }}></c-table-column>
        </WrapTable>
      )
    }
  },
  beforeCreate() {
    const urlArr = ((this.$route.meta && this.$route.meta.children) || []).map(
      item => item.url
    )

    this.addBtns = [
      {
        label: '保存',
        methods: 'handleAddSubmit',
        url: '/v1/yq/sys/roleApi/insert',
        icon: 'el-icon-circle-check-outline',
        type: 'primary',
        disabled: false
      },
      {
        label: '取消',
        methods: 'handleCancel',
        url: '',
        icon: 'el-icon-circle-close-outline',
        disabled: false
      }
    ].filter(item => (item.url && urlArr.includes(item.url)) || !item.url)

    this.editBtns = [
      {
        label: '保存',
        methods: 'handleEditSubmit',
        url: '/v1/yq/sys/roleApi/update',
        icon: 'el-icon-circle-check-outline',
        type: 'primary',
        disabled: false
      },
      {
        label: '取消',
        methods: 'handleCancel',
        url: '',
        icon: 'el-icon-circle-close-outline',
        disabled: false
      }
    ].filter(item => (item.url && urlArr.includes(item.url)) || !item.url)

    this.lookBtns = [
      {
        label: '保存',
        methods: '',
        url: '',
        icon: 'el-icon-circle-check-outline',
        type: 'primary',
        disabled: true
      },
      {
        label: '取消',
        methods: 'handleCancel',
        url: '',
        icon: 'el-icon-circle-close-outline',
        disabled: false
      }
    ].filter(item => (item.url && urlArr.includes(item.url)) || !item.url)

    this.toolPanelBtns = [
      {
        label: '新增',
        methods: 'handleAdd',
        url: '/v1/yq/sys/roleApi/insert',
        icon: 'el-icon-circle-plus-outline',
        type: 'primary',
        disabled: false
      }
      // { label: '删除', methods: 'handleDelGroup',url:'/v1/sys/role/deleteList', icon: 'el-icon-delete', type: 'danger', disabled: false }
    ].filter(item => (item.url && urlArr.includes(item.url)) || !item.url)

    this.tableRowBtnsWithoutEditAndDel = [
      {
        label: '角色授权',
        methods: 'handleAuthorize',
        url: '/v1/sys/role/grantProjectFunction',
        svgIcon: 'roleauthorize',
        type: '',
        key: 'authorize',
        align: 'top-start',
        disabled: false
      },
      {
        label: '人员分配',
        methods: 'handleFenpei',
        url: '/v1/sys/role/grantRoleToUsers',
        svgIcon: 'rolepersonfenpei',
        type: '',
        key: 'fenpei',
        align: 'top-start',
        disabled: false
      }
    ].filter(item => (item.url && urlArr.includes(item.url)) || !item.url)

    // this.tableRowBtns = [
    //     { label: '编辑', methods: 'handleEdit',url:'/v1/yq/sys/roleApi/update', icon: 'el-icon-edit-outline', type: 'primary', key: 'edit', align: 'top-start', disabled: false },
    //     { label: '删除', methods: 'handleDelete',url:'/v1/sys/role/delete', icon: 'el-icon-delete', type: 'danger', key: 'delete', align: 'top-start', disabled: false },
    //     { label: '角色授权', methods: 'handleAuthorize',url:'/v1/sys/role/grantProjectFunction', svgIcon: 'roleauthorize', type: '', key: 'authorize', align: 'top-start', disabled: false },
    //     { label: '人员分配', methods: 'handleFenpei',url:'/v1/sys/role/grantRoleToUsers', svgIcon: 'rolepersonfenpei', type: '', key: 'fenpei', align: 'top-start', disabled: false }
    // ].filter(item => (item.url && urlArr.includes(item.url)) || !item.url)

    this.tableRowBtns2 = [
      {
        label: '编辑',
        methods: 'handleEdit',
        url: '/v1/yq/sys/roleApi/update',
        icon: 'el-icon-edit-outline',
        type: 'primary',
        key: 'edit',
        align: 'top-start',
        disabled: false
      },
      {
        label: '删除',
        methods: 'handleDelete',
        url: '/v1/sys/role/delete',
        icon: 'el-icon-delete',
        type: 'danger',
        key: 'delete',
        align: 'top-start',
        disabled: false
      },
      {
        label: '角色授权',
        methods: 'handleAuthorize',
        url: '/v1/sys/role/grantProjectFunction',
        svgIcon: 'roleauthorize',
        type: '',
        key: 'authorize',
        align: 'top-start',
        disabled: false
      },
      {
        label: '人员分配',
        methods: 'handleFenpei',
        url: '/v1/sys/role/grantRoleToUsers',
        svgIcon: 'rolepersonfenpei',
        type: '',
        key: 'fenpei',
        align: 'top-start',
        disabled: false
      },
      {
        label: '数据组配置',
        methods: 'handleConfig',
        url: '/v1/sys/role/grantRoleToUsers',
        svgIcon: 'datagroupconfig',
        type: '',
        key: 'fenpei',
        align: 'top-start',
        disabled: false
      }
    ].filter(item => (item.url && urlArr.includes(item.url)) || !item.url)

    // render里的按钮
    this.FenpeiBtns = [
      {
        label: '保存',
        methods: 'handleFenpeiSubmit',
        url: '/v1/sys/role/grantRoleToUsers',
        icon: 'el-icon-circle-check-outline',
        type: 'primary',
        disabled: false
      },
      {
        label: '取消',
        methods: 'handleFenpeiCancel',
        url: '',
        icon: 'el-icon-circle-close-outline',
        disabled: false
      }
    ].filter(item => (item.url && urlArr.includes(item.url)) || !item.url)

    this.AuthorizeBtns = [
      {
        label: '保存',
        methods: 'handleAuthorizeSubmit',
        url: '/v1/sys/role/grantProjectFunction',
        icon: 'el-icon-circle-check-outline',
        type: 'primary',
        disabled: false
      },
      {
        label: '取消',
        methods: 'handleAuthorizeCancel',
        url: '',
        icon: 'el-icon-circle-close-outline',
        disabled: false
      }
    ].filter(item => (item.url && urlArr.includes(item.url)) || !item.url)

    this.ConfigBtns = [
      {
        label: '保存',
        methods: 'handleConfigSubmit',
        url: '',
        icon: 'el-icon-circle-check-outline',
        type: 'primary',
        disabled: false
      },
      {
        label: '取消',
        methods: 'handleConfigCancel',
        url: '',
        icon: 'el-icon-circle-close-outline',
        disabled: false
      }
    ].filter(item => (item.url && urlArr.includes(item.url)) || !item.url)
  }
}
</script>

<style lang="scss">
.role-manage {
  .searchPanel {
    display: none;
  }
  .toolPanel {
    .search-input {
      float: right;
      width: 80%;
    }
  }
}
.roleAuthorLoading {
  background: #000;
  opacity: 0.5;
}
.role-authorize-dialog {
  box-sizing: border-box;
  .el-dialog__body {
    height: 500px;
  }
}
</style>
